<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Spring Boot,Spring Security," />










<meta name="description" content="Spring Boot Security源码分析，主要就对2个对象进行分析WebSecurity、HttpSecurity">
<meta name="keywords" content="Spring Boot,Spring Security">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Boot Security源码分析">
<meta property="og:url" content="http://yoursite.com/2018/12/21/Spring-Boot-Security源码分析/Spring-Boot-Security源码分析/index.html">
<meta property="og:site_name" content="程序员乌托邦">
<meta property="og:description" content="Spring Boot Security源码分析，主要就对2个对象进行分析WebSecurity、HttpSecurity">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-12-21T05:15:22.594Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring Boot Security源码分析">
<meta name="twitter:description" content="Spring Boot Security源码分析，主要就对2个对象进行分析WebSecurity、HttpSecurity">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/12/21/Spring-Boot-Security源码分析/Spring-Boot-Security源码分析/"/>





  <title>Spring Boot Security源码分析 | 程序员乌托邦</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">程序员乌托邦</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/12/21/Spring-Boot-Security源码分析/Spring-Boot-Security源码分析/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Wolf、Heart">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="程序员乌托邦">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Spring Boot Security源码分析</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-12-21T13:08:48+08:00">
                2018-12-21
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Spring-Boot/" itemprop="url" rel="index">
                    <span itemprop="name">Spring Boot</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Spring-Security/" itemprop="url" rel="index">
                    <span itemprop="name">Spring Security</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="Spring-Boot-Security源码分析，主要就对2个对象进行分析WebSecurity、HttpSecurity"><a href="#Spring-Boot-Security源码分析，主要就对2个对象进行分析WebSecurity、HttpSecurity" class="headerlink" title="Spring Boot Security源码分析，主要就对2个对象进行分析WebSecurity、HttpSecurity"></a>Spring Boot Security源码分析，主要就对2个对象进行分析WebSecurity、HttpSecurity</h3><a id="more"></a>
<h1 id="一、源码分析"><a href="#一、源码分析" class="headerlink" title="一、源码分析"></a>一、源码分析</h1><p>所有关于Spring Boot Security的教程都会提到一点，就是Spring Boot Security的最重要的部分就是过滤器，比如前面提到过的我们表单登录使用的是UsernamePasswordAuthenticationFilter这个过滤器，然后里面又调用了认证方法来进行认证，但是过滤器是在什么时候加进去的呢？接下来就来分析</p>
<h1 id="二、Spring-Boot-Starter原理"><a href="#二、Spring-Boot-Starter原理" class="headerlink" title="二、Spring Boot Starter原理"></a>二、Spring Boot Starter原理</h1><p>这里再提一下，关于Starter原理，我们知道一般都会有相关的xxxAutoConfiguration类和xxxProperties这两个类，具体可参考<a href="https://github.com/a601942905git/boot-example/tree/master/boot-example-custom-starter" target="_blank" rel="noopener">Spring Boot Starter原理</a></p>
<h1 id="三、套路"><a href="#三、套路" class="headerlink" title="三、套路"></a>三、套路</h1><p>在项目中搜索SecurityAutoConfiguration这样的字眼，在搜索的列表中我们可以看到大致我们需要的有<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SecurityAutoConfiguration</span><br><span class="line"></span><br><span class="line">SecurityFilterAutoConfiguration</span><br></pre></td></tr></table></figure></p>
<h1 id="四、SecurityFilterAutoConfiguration"><a href="#四、SecurityFilterAutoConfiguration" class="headerlink" title="四、SecurityFilterAutoConfiguration"></a>四、SecurityFilterAutoConfiguration</h1><p>看到这个名字我们大胆猜测下和我们需要查找的宝藏Filter有一定的关联，名字看着就像，接下来看看该类的代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">@ConditionalOnWebApplication(type = Type.SERVLET)</span><br><span class="line">@EnableConfigurationProperties(SecurityProperties.class)</span><br><span class="line">@ConditionalOnClass(&#123; AbstractSecurityWebApplicationInitializer.class,</span><br><span class="line">		SessionCreationPolicy.class &#125;)</span><br><span class="line">@AutoConfigureAfter(SecurityAutoConfiguration.class)</span><br></pre></td></tr></table></figure></p>
<p>首先看看这一坨注解，对于这些引入的注解也是很有用的，会加载一些额外的信息，我们不能忽视</p>
<p>关于SecurityProperties这个就没什么好说的了，就是关于Security的一些配置</p>
<p>关于AbstractSecurityWebApplicationInitializer，接下来我们重点看下</p>
<h1 id="AbstractSecurityWebApplicationInitializer"><a href="#AbstractSecurityWebApplicationInitializer" class="headerlink" title="AbstractSecurityWebApplicationInitializer"></a>AbstractSecurityWebApplicationInitializer</h1><p>看到这个类的名称我们大概也能猜出大致的意思，就是应用启动初始化操作</p>
<p>首先看到如下代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">public static final String DEFAULT_FILTER_NAME = &quot;springSecurityFilterChain&quot;;</span><br></pre></td></tr></table></figure></p>
<p>我们可以看到定义了默认的Filter名称为springSecurityFilterChain，继续往下翻看代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">public final void onStartup(ServletContext servletContext) throws ServletException &#123;</span><br><span class="line">	beforeSpringSecurityFilterChain(servletContext);</span><br><span class="line">	if (this.configurationClasses != null) &#123;</span><br><span class="line">		AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext();</span><br><span class="line">		rootAppContext.register(this.configurationClasses);</span><br><span class="line">		servletContext.addListener(new ContextLoaderListener(rootAppContext));</span><br><span class="line">	&#125;</span><br><span class="line">	if (enableHttpSessionEventPublisher()) &#123;</span><br><span class="line">		servletContext.addListener(</span><br><span class="line">				&quot;org.springframework.security.web.session.HttpSessionEventPublisher&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	servletContext.setSessionTrackingModes(getSessionTrackingModes());</span><br><span class="line">	insertSpringSecurityFilterChain(servletContext);</span><br><span class="line">	afterSpringSecurityFilterChain(servletContext);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>有个onStartup方法，肯定是在应用启动的时候执行的，我们需要看看该方法具体干了什么？</p>
<p>着重看下这行代码，这个名字告诉我们是插入SpringSecurityFilterChain的<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">insertSpringSecurityFilterChain(servletContext);</span><br></pre></td></tr></table></figure></p>
<p>查看该方法的具体实现<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">private void insertSpringSecurityFilterChain(ServletContext servletContext) &#123;</span><br><span class="line">	String filterName = DEFAULT_FILTER_NAME;</span><br><span class="line">	DelegatingFilterProxy springSecurityFilterChain = new DelegatingFilterProxy(</span><br><span class="line">			filterName);</span><br><span class="line">	String contextAttribute = getWebApplicationContextAttribute();</span><br><span class="line">	if (contextAttribute != null) &#123;</span><br><span class="line">		springSecurityFilterChain.setContextAttribute(contextAttribute);</span><br><span class="line">	&#125;</span><br><span class="line">	registerFilter(servletContext, true, filterName, springSecurityFilterChain);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>创建了一个DelegatingFilterProxy这样一个Filter对象，名称为springSecurityFilterChain，然后关注下面这行代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">registerFilter(servletContext, true, filterName, springSecurityFilterChain);</span><br></pre></td></tr></table></figure></p>
<p>这行代码就是注册Fliter的<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">private final void registerFilter(ServletContext servletContext,</span><br><span class="line">			boolean insertBeforeOtherFilters, String filterName, Filter filter) &#123;</span><br><span class="line">	Dynamic registration = servletContext.addFilter(filterName, filter);</span><br><span class="line">	if (registration == null) &#123;</span><br><span class="line">		throw new IllegalStateException(</span><br><span class="line">				&quot;Duplicate Filter registration for &apos;&quot; + filterName</span><br><span class="line">						+ &quot;&apos;. Check to ensure the Filter is only configured once.&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	registration.setAsyncSupported(isAsyncSecuritySupported());</span><br><span class="line">	EnumSet&lt;DispatcherType&gt; dispatcherTypes = getSecurityDispatcherTypes();</span><br><span class="line">	registration.addMappingForUrlPatterns(dispatcherTypes, !insertBeforeOtherFilters,</span><br><span class="line">			&quot;/*&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>通过ServletContext添加Filter<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Dynamic registration = servletContext.addFilter(filterName, filter);</span><br></pre></td></tr></table></figure></p>
<p>设置Filter是否支持异步属性<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">registration.setAsyncSupported(isAsyncSecuritySupported());</span><br></pre></td></tr></table></figure></p>
<p>设置Filter的拦截路径<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">registration.addMappingForUrlPatterns(dispatcherTypes, !insertBeforeOtherFilters,</span><br><span class="line">				&quot;/*&quot;);</span><br></pre></td></tr></table></figure></p>
<p>到这里我们可以看到已经添加了一个DelegatingFilterProxy这样一个过滤器，名称为springSecurityFilterChain</p>
<h1 id="SecurityAutoConfiguration"><a href="#SecurityAutoConfiguration" class="headerlink" title="SecurityAutoConfiguration"></a>SecurityAutoConfiguration</h1><p>打开这个类，可以看到又一坨的注解<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">@ConditionalOnClass(DefaultAuthenticationEventPublisher.class)</span><br><span class="line">@EnableConfigurationProperties(SecurityProperties.class)</span><br><span class="line">@Import(&#123; SpringBootWebSecurityConfiguration.class, WebSecurityEnablerConfiguration.class,</span><br><span class="line">		SecurityDataConfiguration.class &#125;)</span><br></pre></td></tr></table></figure></p>
<p>我们点这个WebSecurityEnablerConfiguration进去看看<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">@ConditionalOnBean(WebSecurityConfigurerAdapter.class)</span><br><span class="line">@ConditionalOnMissingBean(name = BeanIds.SPRING_SECURITY_FILTER_CHAIN)</span><br><span class="line">@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)</span><br><span class="line">@EnableWebSecurity</span><br><span class="line">public class WebSecurityEnablerConfiguration &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>看到一个很熟悉的注解@EnableWebSecurity，看到好多教程里面都有这个注解，不知道是不是因为版本的原因，网上的教程都需要手动添加该注解来启用Security功能，但是现在我们不需要了，引入Starter之后就会含有该注解，我使用的Boot版本为2.1.0.RELEASE</p>
<p>点击@EnableWebSecurity注解进去，又看到一坨坨注解<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)</span><br><span class="line">@Target(value = &#123; java.lang.annotation.ElementType.TYPE &#125;)</span><br><span class="line">@Documented</span><br><span class="line">@Import(&#123; WebSecurityConfiguration.class,</span><br><span class="line">		SpringWebMvcImportSelector.class,</span><br><span class="line">		OAuth2ImportSelector.class &#125;)</span><br><span class="line">@EnableGlobalAuthentication</span><br><span class="line">@Configuration</span><br><span class="line">public @interface EnableWebSecurity &#123;</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	 * Controls debugging support for Spring Security. Default is false.</span><br><span class="line">	 * @return if true, enables debug support with Spring Security</span><br><span class="line">	 */</span><br><span class="line">	boolean debug() default false;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>点@WebSecurityConfiguration这个注解进去看看<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">@Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)</span><br><span class="line">	public Filter springSecurityFilterChain() throws Exception &#123;</span><br><span class="line">	boolean hasConfigurers = webSecurityConfigurers != null</span><br><span class="line">			&amp;&amp; !webSecurityConfigurers.isEmpty();</span><br><span class="line">	if (!hasConfigurers) &#123;</span><br><span class="line">		WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor</span><br><span class="line">				.postProcess(new WebSecurityConfigurerAdapter() &#123;</span><br><span class="line">				&#125;);</span><br><span class="line">		webSecurity.apply(adapter);</span><br><span class="line">	&#125;</span><br><span class="line">	return webSecurity.build();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>如上会调用webSecurity.build()方法，那么webSecurity这个对象是如何初始化的，往下翻我们会看到如下代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">@Autowired(required = false)</span><br><span class="line">public void setFilterChainProxySecurityConfigurer(</span><br><span class="line">		ObjectPostProcessor&lt;Object&gt; objectPostProcessor,</span><br><span class="line">		@Value(&quot;#&#123;@autowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers()&#125;&quot;) List&lt;SecurityConfigurer&lt;Filter, WebSecurity&gt;&gt; webSecurityConfigurers)</span><br><span class="line">		throws Exception &#123;</span><br><span class="line">	webSecurity = objectPostProcessor</span><br><span class="line">			.postProcess(new WebSecurity(objectPostProcessor));</span><br><span class="line">	if (debugEnabled != null) &#123;</span><br><span class="line">		webSecurity.debug(debugEnabled);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	Collections.sort(webSecurityConfigurers, AnnotationAwareOrderComparator.INSTANCE);</span><br><span class="line"></span><br><span class="line">	Integer previousOrder = null;</span><br><span class="line">	Object previousConfig = null;</span><br><span class="line">	for (SecurityConfigurer&lt;Filter, WebSecurity&gt; config : webSecurityConfigurers) &#123;</span><br><span class="line">		Integer order = AnnotationAwareOrderComparator.lookupOrder(config);</span><br><span class="line">		if (previousOrder != null &amp;&amp; previousOrder.equals(order)) &#123;</span><br><span class="line">			throw new IllegalStateException(</span><br><span class="line">					&quot;@Order on WebSecurityConfigurers must be unique. Order of &quot;</span><br><span class="line">							+ order + &quot; was already used on &quot; + previousConfig + &quot;, so it cannot be used on &quot;</span><br><span class="line">							+ config + &quot; too.&quot;);</span><br><span class="line">		&#125;</span><br><span class="line">		previousOrder = order;</span><br><span class="line">		previousConfig = config;</span><br><span class="line">	&#125;</span><br><span class="line">	for (SecurityConfigurer&lt;Filter, WebSecurity&gt; webSecurityConfigurer : webSecurityConfigurers) &#123;</span><br><span class="line">		webSecurity.apply(webSecurityConfigurer);</span><br><span class="line">	&#125;</span><br><span class="line">	this.webSecurityConfigurers = webSecurityConfigurers;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们首先关注下如下代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">webSecurity = objectPostProcessor</span><br><span class="line">				.postProcess(new WebSecurity(objectPostProcessor));</span><br></pre></td></tr></table></figure></p>
<p>通过断点我们可以看到postProcess()方法的实际调用者是AutowireBeanFactoryObjectPostProcessor，我们来查看下该类的方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">public &lt;T&gt; T postProcess(T object) &#123;</span><br><span class="line">	if (object == null) &#123;</span><br><span class="line">		return null;</span><br><span class="line">	&#125;</span><br><span class="line">	T result = null;</span><br><span class="line">	try &#123;</span><br><span class="line">		result = (T) this.autowireBeanFactory.initializeBean(object,</span><br><span class="line">				object.toString());</span><br><span class="line">	&#125;</span><br><span class="line">	catch (RuntimeException e) &#123;</span><br><span class="line">		Class&lt;?&gt; type = object.getClass();</span><br><span class="line">		throw new RuntimeException(</span><br><span class="line">				&quot;Could not postProcess &quot; + object + &quot; of type &quot; + type, e);</span><br><span class="line">	&#125;</span><br><span class="line">	this.autowireBeanFactory.autowireBean(object);</span><br><span class="line">	if (result instanceof DisposableBean) &#123;</span><br><span class="line">		this.disposableBeans.add((DisposableBean) result);</span><br><span class="line">	&#125;</span><br><span class="line">	if (result instanceof SmartInitializingSingleton) &#123;</span><br><span class="line">		this.smartSingletons.add((SmartInitializingSingleton) result);</span><br><span class="line">	&#125;</span><br><span class="line">	return result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们来看下这段代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">this.autowireBeanFactory.initializeBean(object,</span><br><span class="line">				object.toString());</span><br></pre></td></tr></table></figure></p>
<p>初始化WebSecurity Bean，然后返回WebSecurity对象</p>
<p>回到刚才的setFilterChainProxySecurityConfigurer()方法，再看下这部分代码，通过断点查看我们可得知这里的webSecurityConfigurer就是我们自定义的security配置类，继承了WebSecurityConfigurerAdapter<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">for (SecurityConfigurer&lt;Filter, WebSecurity&gt; webSecurityConfigurer : webSecurityConfigurers) &#123;</span><br><span class="line">	webSecurity.apply(webSecurityConfigurer);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>点击apply()方法，进去之后代码如下<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public &lt;C extends SecurityConfigurer&lt;O, B&gt;&gt; C apply(C configurer) throws Exception &#123;</span><br><span class="line">	add(configurer);</span><br><span class="line">	return configurer;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在来看下add(configurer)方法，里面有一段这样的代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">this.configurers.put(clazz, configs);</span><br></pre></td></tr></table></figure></p>
<p>可以看出来实际上就是将我们定义的security配置类放入了AbstractConfiguredSecurityBuilder中configurers这样一个map集合中</p>
<p>接下来回到我们WebSecurityConfiguration的springSecurityFilterChain()方法中，继续分析我们的代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">return webSecurity.build();</span><br></pre></td></tr></table></figure></p>
<p>点击build()方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public final O build() throws Exception &#123;</span><br><span class="line">	if (this.building.compareAndSet(false, true)) &#123;</span><br><span class="line">		this.object = doBuild();</span><br><span class="line">		return this.object;</span><br><span class="line">	&#125;</span><br><span class="line">	throw new AlreadyBuiltException(&quot;This object has already been built&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>然后点击doBuild()方法，记住该doBuild()方法是属于WebSecurity对象的，来看看doBuild()方法都做了什么<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">protected final O doBuild() throws Exception &#123;</span><br><span class="line">	synchronized (configurers) &#123;</span><br><span class="line">		buildState = BuildState.INITIALIZING;</span><br><span class="line"></span><br><span class="line">		beforeInit();</span><br><span class="line">		init();</span><br><span class="line"></span><br><span class="line">		buildState = BuildState.CONFIGURING;</span><br><span class="line"></span><br><span class="line">		beforeConfigure();</span><br><span class="line">		configure();</span><br><span class="line"></span><br><span class="line">		buildState = BuildState.BUILDING;</span><br><span class="line"></span><br><span class="line">		O result = performBuild();</span><br><span class="line"></span><br><span class="line">		buildState = BuildState.BUILT;</span><br><span class="line"></span><br><span class="line">		return result;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>大体分析一下做了3件事情</p>
<ol>
<li>初始化</li>
<li>配置</li>
<li>构建对象返回</li>
</ol>
<p>首先看下初始化方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">private void init() throws Exception &#123;</span><br><span class="line">	Collection&lt;SecurityConfigurer&lt;O, B&gt;&gt; configurers = getConfigurers();</span><br><span class="line"></span><br><span class="line">	for (SecurityConfigurer&lt;O, B&gt; configurer : configurers) &#123;</span><br><span class="line">		configurer.init((B) this);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	for (SecurityConfigurer&lt;O, B&gt; configurer : configurersAddedInInitializing) &#123;</span><br><span class="line">		configurer.init((B) this);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>看下getConfigurers()这个方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">private Collection&lt;SecurityConfigurer&lt;O, B&gt;&gt; getConfigurers() &#123;</span><br><span class="line">	List&lt;SecurityConfigurer&lt;O, B&gt;&gt; result = new ArrayList&lt;SecurityConfigurer&lt;O, B&gt;&gt;();</span><br><span class="line">	for (List&lt;SecurityConfigurer&lt;O, B&gt;&gt; configs : this.configurers.values()) &#123;</span><br><span class="line">		result.addAll(configs);</span><br><span class="line">	&#125;</span><br><span class="line">	return result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>该方法就是把我们放入map中自定义的security配置，拿出来，放到集合中</p>
<p>回到刚才的init()方法，继续看configure.init((B)this)方法，就是调用我们自定义security配置类的init()方法，我们自定义的配置类又继承了WebSecurityConfigurerAdapter，所以直接定位到该类的init()方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public void init(final WebSecurity web) throws Exception &#123;</span><br><span class="line">	final HttpSecurity http = getHttp();</span><br><span class="line">	web.addSecurityFilterChainBuilder(http).postBuildAction(new Runnable() &#123;</span><br><span class="line">		public void run() &#123;</span><br><span class="line">			FilterSecurityInterceptor securityInterceptor = http</span><br><span class="line">					.getSharedObject(FilterSecurityInterceptor.class);</span><br><span class="line">			web.securityInterceptor(securityInterceptor);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>该方法首先调用了getHttp()方法，然后返回一个HttpSecurity对象，然后把HttpSecurity对象放入了WebSecurity对象的securityFilterChainBuilders集合中，并且指明了postBuildAction要执行的逻辑，后面会进行调用</p>
<p>重点关注一下getHttp()方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">http</span><br><span class="line">	.csrf().and()</span><br><span class="line">	.addFilter(new WebAsyncManagerIntegrationFilter())</span><br><span class="line">	.exceptionHandling().and()</span><br><span class="line">	.headers().and()</span><br><span class="line">	.sessionManagement().and()</span><br><span class="line">	.securityContext().and()</span><br><span class="line">	.requestCache().and()</span><br><span class="line">	.anonymous().and()</span><br><span class="line">	.servletApi().and()</span><br><span class="line">	.apply(new DefaultLoginPageConfigurer&lt;&gt;()).and()</span><br><span class="line">	.logout();</span><br></pre></td></tr></table></figure></p>
<p>里面有这样的一段的代码，我们点击csrf()进去看下<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public CsrfConfigurer&lt;HttpSecurity&gt; csrf() throws Exception &#123;</span><br><span class="line">	ApplicationContext context = getContext();</span><br><span class="line">	return getOrApply(new CsrfConfigurer&lt;&gt;(context));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>也就是如果configure不存在，就放入map集合中，跟之前把我们自定义的security放入map中是一个道理。同理exceptionHandling()方法点进去也是往map中放入对应的configure，断点查看会放入差多10个左右的configure在map中，后面会使用到。目前WebSecurity的map集合放了一个我们自定义的security配置，HttpSecurity放了差不多10个左右的configure在map中，不要搞混淆了。</p>
<p>继续查看performBuild()，也就是WebSecurity的performBuild()方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">protected Filter performBuild() throws Exception &#123;</span><br><span class="line">	Assert.state(</span><br><span class="line">			!securityFilterChainBuilders.isEmpty(),</span><br><span class="line">			() -&gt; &quot;At least one SecurityBuilder&lt;? extends SecurityFilterChain&gt; needs to be specified. &quot;</span><br><span class="line">					+ &quot;Typically this done by adding a @Configuration that extends WebSecurityConfigurerAdapter. &quot;</span><br><span class="line">					+ &quot;More advanced users can invoke &quot;</span><br><span class="line">					+ WebSecurity.class.getSimpleName()</span><br><span class="line">					+ &quot;.addSecurityFilterChainBuilder directly&quot;);</span><br><span class="line">	int chainSize = ignoredRequests.size() + securityFilterChainBuilders.size();</span><br><span class="line">	List&lt;SecurityFilterChain&gt; securityFilterChains = new ArrayList&lt;&gt;(</span><br><span class="line">			chainSize);</span><br><span class="line">	for (RequestMatcher ignoredRequest : ignoredRequests) &#123;</span><br><span class="line">		securityFilterChains.add(new DefaultSecurityFilterChain(ignoredRequest));</span><br><span class="line">	&#125;</span><br><span class="line">	for (SecurityBuilder&lt;? extends SecurityFilterChain&gt; securityFilterChainBuilder : securityFilterChainBuilders) &#123;</span><br><span class="line">		securityFilterChains.add(securityFilterChainBuilder.build());</span><br><span class="line">	&#125;</span><br><span class="line">	FilterChainProxy filterChainProxy = new FilterChainProxy(securityFilterChains);</span><br><span class="line">	if (httpFirewall != null) &#123;</span><br><span class="line">		filterChainProxy.setFirewall(httpFirewall);</span><br><span class="line">	&#125;</span><br><span class="line">	filterChainProxy.afterPropertiesSet();</span><br><span class="line"></span><br><span class="line">	Filter result = filterChainProxy;</span><br><span class="line">	if (debugEnabled) &#123;</span><br><span class="line">		logger.warn(&quot;\n\n&quot;</span><br><span class="line">				+ &quot;********************************************************************\n&quot;</span><br><span class="line">				+ &quot;**********        Security debugging is enabled.       *************\n&quot;</span><br><span class="line">				+ &quot;**********    This may include sensitive information.  *************\n&quot;</span><br><span class="line">				+ &quot;**********      Do not use in a production system!     *************\n&quot;</span><br><span class="line">				+ &quot;********************************************************************\n\n&quot;);</span><br><span class="line">		result = new DebugFilter(filterChainProxy);</span><br><span class="line">	&#125;</span><br><span class="line">	postBuildAction.run();</span><br><span class="line">	return result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>看下下面这段代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">for (SecurityBuilder&lt;? extends SecurityFilterChain&gt; securityFilterChainBuilder : securityFilterChainBuilders) &#123;</span><br><span class="line">	securityFilterChains.add(securityFilterChainBuilder.build());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们知道securityFilterChainBuilders这个集合里面放的就是HttpSecurity，在之前的init()方法中放入进去的，后面紧跟一个build()方法，也就是执行了刚才的build()—&gt;doBuild()</p>
<p>接下来就开始分析HttpSecurity的doBuild()方法</p>
<ol>
<li>init()方法，里面会遍历之前放入map中的configure，大概10个左右，举个例子LogoutConfigurer，退出登录<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public void init(H http) throws Exception &#123;</span><br><span class="line">	if (permitAll) &#123;</span><br><span class="line">		PermitAllSupport.permitAll(http, this.logoutSuccessUrl);</span><br><span class="line">		PermitAllSupport.permitAll(http, this.getLogoutRequestMatcher(http));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http</span><br><span class="line">			.getSharedObject(DefaultLoginPageGeneratingFilter.class);</span><br><span class="line">	if (loginPageGeneratingFilter != null &amp;&amp; !isCustomLogoutSuccess()) &#123;</span><br><span class="line">		loginPageGeneratingFilter.setLogoutSuccessUrl(getLogoutSuccessUrl());</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>主要做一下初始化配置</p>
<ol start="2">
<li>configire()方法，还是拿LogoutConfigurer来举例<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public void configure(H http) throws Exception &#123;</span><br><span class="line">	LogoutFilter logoutFilter = createLogoutFilter(http);</span><br><span class="line">	http.addFilter(logoutFilter);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>我们可以看到创建过滤器对象，然后放入HttpSecurity对象的filters集合变量中</p>
<ol start="3">
<li>performBuild()方法<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">protected DefaultSecurityFilterChain performBuild() throws Exception &#123;</span><br><span class="line">	Collections.sort(filters, comparator);</span><br><span class="line">	return new DefaultSecurityFilterChain(requestMatcher, filters);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>构建DefaultSecurityFilterChain对象，并设置filters集合变量</p>
<p>HttpSecurity build完成之后，回到WebSecurity的performBuild()方法中<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">FilterChainProxy filterChainProxy = new FilterChainProxy(securityFilterChains);</span><br></pre></td></tr></table></figure></p>
<p>此上构建了一个FilterChainProxy对象，将DefaultSecurityFilterChain放入了其中</p>
<p>再往下看<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">postBuildAction.run();</span><br></pre></td></tr></table></figure></p>
<p>之前在WebSecurity build的init()方法在构建HttpSecurity的时候有指定了postBuildAction的代码逻辑，再来回顾一下代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public void init(final WebSecurity web) throws Exception &#123;</span><br><span class="line">	final HttpSecurity http = getHttp();</span><br><span class="line">	web.addSecurityFilterChainBuilder(http).postBuildAction(new Runnable() &#123;</span><br><span class="line">		public void run() &#123;</span><br><span class="line">			FilterSecurityInterceptor securityInterceptor = http</span><br><span class="line">					.getSharedObject(FilterSecurityInterceptor.class);</span><br><span class="line">			web.securityInterceptor(securityInterceptor);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>获取FilterSecurityInterceptor对象，设置WebSecurity的filterSecurityInterceptor</p>
<p>回到最初的代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">@Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)</span><br><span class="line">public Filter springSecurityFilterChain() throws Exception &#123;</span><br><span class="line">	boolean hasConfigurers = webSecurityConfigurers != null</span><br><span class="line">			&amp;&amp; !webSecurityConfigurers.isEmpty();</span><br><span class="line">	if (!hasConfigurers) &#123;</span><br><span class="line">		WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor</span><br><span class="line">				.postProcess(new WebSecurityConfigurerAdapter() &#123;</span><br><span class="line">				&#125;);</span><br><span class="line">		webSecurity.apply(adapter);</span><br><span class="line">	&#125;</span><br><span class="line">	return webSecurity.build();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>通过如上的分析，得知webSecurity.build()返回的是一个filterChainProxy这样的一个过滤器，拦截所有的请求</p>
<p>下面分析FilterChainProxy的doFilterInternal()方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">private void doFilterInternal(ServletRequest request, ServletResponse response,</span><br><span class="line">	FilterChain chain) throws IOException, ServletException &#123;</span><br><span class="line"></span><br><span class="line">FirewalledRequest fwRequest = firewall</span><br><span class="line">		.getFirewalledRequest((HttpServletRequest) request);</span><br><span class="line">HttpServletResponse fwResponse = firewall</span><br><span class="line">		.getFirewalledResponse((HttpServletResponse) response);</span><br><span class="line"></span><br><span class="line">List&lt;Filter&gt; filters = getFilters(fwRequest);</span><br><span class="line"></span><br><span class="line">if (filters == null || filters.size() == 0) &#123;</span><br><span class="line">	if (logger.isDebugEnabled()) &#123;</span><br><span class="line">		logger.debug(UrlUtils.buildRequestUrl(fwRequest)</span><br><span class="line">				+ (filters == null ? &quot; has no matching filters&quot;</span><br><span class="line">						: &quot; has an empty filter list&quot;));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	fwRequest.reset();</span><br><span class="line"></span><br><span class="line">	chain.doFilter(fwRequest, fwResponse);</span><br><span class="line"></span><br><span class="line">	return;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">VirtualFilterChain vfc = new VirtualFilterChain(fwRequest, chain, filters);</span><br><span class="line">vfc.doFilter(fwRequest, fwResponse);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>看最后一行VirtualFilterChain vfc = new VirtualFilterChain(fwRequest, chain, filters);</p>
<p>看下的VirtualFilterChain的doFilter()方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public void doFilter(ServletRequest request, ServletResponse response)</span><br><span class="line">		throws IOException, ServletException &#123;</span><br><span class="line">	if (currentPosition == size) &#123;</span><br><span class="line">		if (logger.isDebugEnabled()) &#123;</span><br><span class="line">			logger.debug(UrlUtils.buildRequestUrl(firewalledRequest)</span><br><span class="line">					+ &quot; reached end of additional filter chain; proceeding with original chain&quot;);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		// Deactivate path stripping as we exit the security filter chain</span><br><span class="line">		this.firewalledRequest.reset();</span><br><span class="line"></span><br><span class="line">		originalChain.doFilter(request, response);</span><br><span class="line">	&#125;</span><br><span class="line">	else &#123;</span><br><span class="line">		currentPosition++;</span><br><span class="line"></span><br><span class="line">		Filter nextFilter = additionalFilters.get(currentPosition - 1);</span><br><span class="line"></span><br><span class="line">		if (logger.isDebugEnabled()) &#123;</span><br><span class="line">			logger.debug(UrlUtils.buildRequestUrl(firewalledRequest)</span><br><span class="line">					+ &quot; at position &quot; + currentPosition + &quot; of &quot; + size</span><br><span class="line">					+ &quot; in additional filter chain; firing Filter: &apos;&quot;</span><br><span class="line">					+ nextFilter.getClass().getSimpleName() + &quot;&apos;&quot;);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		nextFilter.doFilter(request, response, this);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>如上我们可以得知，FilterChainProxy中拥有很多过滤器，但是这些过滤器都是没有注册的，都使用FilterChainProxy这一个dialing来模拟过滤器链。当执行到的过滤器不是最后一个，那么继续使用FilterChainProxy往下链，执行的还是自己的doFilter，如果执行到最后一个过滤器，那么执行其他过滤器的doFilter。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Spring-Boot/" rel="tag"># Spring Boot</a>
          
            <a href="/tags/Spring-Security/" rel="tag"># Spring Security</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/12/20/Spring-Boot-Security分析/Spring-Boot-Security分析/" rel="next" title="Spring Boot Security分析">
                <i class="fa fa-chevron-left"></i> Spring Boot Security分析
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Wolf、Heart</p>
              <p class="site-description motion-element" itemprop="description">主要用于分享平时学习的只是以及遇到的困难，帮助自己以及需要的人一起共同成长</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">45</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">14</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Spring-Boot-Security源码分析，主要就对2个对象进行分析WebSecurity、HttpSecurity"><span class="nav-number">1.</span> <span class="nav-text">Spring Boot Security源码分析，主要就对2个对象进行分析WebSecurity、HttpSecurity</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#一、源码分析"><span class="nav-number"></span> <span class="nav-text">一、源码分析</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二、Spring-Boot-Starter原理"><span class="nav-number"></span> <span class="nav-text">二、Spring Boot Starter原理</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#三、套路"><span class="nav-number"></span> <span class="nav-text">三、套路</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#四、SecurityFilterAutoConfiguration"><span class="nav-number"></span> <span class="nav-text">四、SecurityFilterAutoConfiguration</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#AbstractSecurityWebApplicationInitializer"><span class="nav-number"></span> <span class="nav-text">AbstractSecurityWebApplicationInitializer</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#SecurityAutoConfiguration"><span class="nav-number"></span> <span class="nav-text">SecurityAutoConfiguration</span></a></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Wolf、Heart</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
